﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using Infragistics.Documents.Excel;

namespace ibba.src.norisk.Controls
{
    public partial class ControlRelImportParametros : UserControl
    {
        public List<ServiceContratoVigencia.ContratoVigencia> _oContratos;
        public static Page ParentPage { get; set; }

        public ControlRelImportParametros()
        {
            InitializeComponent();
        }

        private void btnGerarRelatorio_Click(object sender, RoutedEventArgs e)
        {
            BuscaDados();
        }

        private void BuscaDados()
        {
            if (this.dtpDtFim.SelectedDate.HasValue && this.dtpDtInicio.SelectedDate.HasValue)
            {
                if (this.dtpDtFim.SelectedDate < this.dtpDtInicio.SelectedDate)
                {
                    MessageBoxHelper.ShowMessage("Aviso", "Campo data fim não pode ser menor que o campo data início");
                }
                else
                {
                    ((ibba.src.norisk.page.PageRelatorios)(ParentPage)).ExibeCarregando(true, "Aguarde...");

                    ServiceFactory.GetInstance().ServiceContratoVigencia.BeginListarContratoVigenciaLog(this.dtpDtInicio.SelectedDate.Value,
                        this.dtpDtFim.SelectedDate.Value, CallBackListarContratoVigenciaLog,
                        ServiceFactory.GetInstance().ServiceContratoVigencia);
                }
            }
            else
            {
                MessageBoxHelper.ShowMessage("Aviso", "Preencha os campos de pesquisa corretamente");
            }
        }

        private void GeraPlanilha()
        {
            try
            {
                SaveFileDialog dialog = new SaveFileDialog();

                dialog.Filter = "Excel Worksheets 2003 (*.xls, *.xlsx)|*.xls;*.xlsx|Csv files (*.csv)|*.csv";
                bool? retval = dialog.ShowDialog();

                if (retval != null && retval == true)
                {
                    using (Stream stream = dialog.OpenFile())
                    {
                        Workbook excelFile = ExportarWorkbook();
                        excelFile.Save(stream);

                        stream.Close();

                        MessageBoxHelper.ShowSucess("Sucesso", "Arquivo " + dialog.SafeFileName + " gerado com sucesso.");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                ((ibba.src.norisk.page.PageRelatorios)(ParentPage)).ExibeCarregando(false, null);
            }
        }

        private Workbook ExportarWorkbook()
        {
            Workbook workBook = new Workbook();
            Worksheet workSheet = null;
            int _lin = 0;
            int _ws = 1;

            if (_oContratos != null)
            {
                foreach (ServiceContratoVigencia.ContratoVigencia item in _oContratos)
                {
                    if (_lin == 0)
                    {
                        workSheet = workBook.Worksheets.Add(string.Concat("ImpParametros", _ws.ToString()));

                        workSheet.Rows[0].Cells[0].Value = "Grupo";
                        workSheet.Rows[0].Cells[0].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[1].Value = "Cliente";
                        workSheet.Rows[0].Cells[1].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[2].Value = "Contrato";
                        workSheet.Rows[0].Cells[2].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[3].Value = "Parâmetro Alterado";
                        workSheet.Rows[0].Cells[3].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[4].Value = "Vl. Parâmetro";
                        workSheet.Rows[0].Cells[4].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[5].Value = "Usuário";
                        workSheet.Rows[0].Cells[5].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[6].Value = "Data de Alteração";
                        workSheet.Rows[0].Cells[6].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[7].Value = "Data de Início";
                        workSheet.Rows[0].Cells[7].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        workSheet.Rows[0].Cells[8].Value = "Data de Término";
                        workSheet.Rows[0].Cells[8].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                        //workSheet.Rows[0].Cells[7].Value = "Ação";
                        //workSheet.Rows[0].Cells[7].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                    }

                    ++_lin;

                    workSheet.Rows[_lin].Cells[0].Value = item.NmGrupoCliente;
                    workSheet.Rows[_lin].Cells[1].Value = item.NmCliente;
                    workSheet.Rows[_lin].Cells[2].Value = item.CdContrato;
                    workSheet.Rows[_lin].Cells[3].Value = item.DscParametro;
                    workSheet.Rows[_lin].Cells[4].Value = item.VlrParametro;
                    workSheet.Rows[_lin].Cells[5].Value = item.CdUsuario.ToString();
                    workSheet.Rows[_lin].Cells[6].Value = item.DtLog.Value.ToString("dd/MM/yyyy");
                    workSheet.Rows[_lin].Cells[7].Value = item.DtInicio.ToString("dd/MM/yyyy");
                    workSheet.Rows[_lin].Cells[8].Value = item.DtTermino.HasValue ? item.DtTermino.Value.ToString("dd/MM/yyyy") : null;
                    //workSheet.Rows[_lin].Cells[9].Value = item.TpAcao.ToString();

                    if (_lin >= 65535)
                    {
                        _lin = 0;
                        ++_ws;
                    }
                }
            }
            return workBook;
        }

        private void CallBackListarContratoVigenciaLog(IAsyncResult pAsyncResult)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                try
                {
                    _oContratos = ((ServiceContratoVigencia.IContratoVigencia)pAsyncResult.AsyncState).EndListarContratoVigenciaLog(pAsyncResult);

                    if (_oContratos.Count > 0)
                    {
                        MessageBoxHelper.ShowQuestion("Sucesso", "Dados gerados com sucesso. Confirme a exportação do relatório", window_OnMessageBoxClosed);
                    }
                    else
                    {
                        MessageBoxHelper.ShowMessage("Aviso", "Dados não localizados");
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    ((ibba.src.norisk.page.PageRelatorios)(ParentPage)).ExibeCarregando(false, null);
                }
            });
        }

        private void ExibeCarregando(bool enable, string busyContent)
        {
            activity.BusyContent = busyContent;
            activity.IsBusy = enable;
        }

        void window_OnMessageBoxClosed(MessageBoxResult result)
        {
            if (result == MessageBoxResult.Yes)
            {
                var parent = this.Parent;

                ((ibba.src.norisk.page.PageRelatorios)(ParentPage)).ExibeCarregando(true, "Carregando...");
                this.GeraPlanilha();
            }
        }
    }
}
